package com.qxl.forest.core.auth.controller;

import com.qxl.forest.core.exception.BizExceptionEnum;
import com.qxl.forest.core.exception.BussinessException;
import com.qxl.forest.core.auth.controller.dto.AuthRequest;
import com.qxl.forest.core.auth.controller.dto.AuthResponse;
import com.qxl.forest.core.util.JwtTokenUtil;
import com.qxl.forest.core.auth.validator.IReqValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: qiuxinlin
 * @Dercription: 请求验证的控制器
 * @Date: 2018/1/5
 */
@RestController
public class AuthController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource(name = "simpleValidator")
    private IReqValidator reqValidator;

    @PostMapping(value = "${jwt.auth-path}")
    public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthRequest authRequest) {

        boolean validate = reqValidator.validate(authRequest);

        if (validate) {
            final String randomKey = jwtTokenUtil.getRandomKey();
            final String token = jwtTokenUtil.generateToken(authRequest.getAccount(), randomKey);
            return ResponseEntity.ok(new AuthResponse(token, randomKey));

        } else {
            throw new BussinessException(BizExceptionEnum.AUTH_REQUEST_ERROR);
        }
    }
}
